#include "formpz_fj.h"
#include "ui_formpz_fj.h"
#include <formcam.h>
#include <mysql.h>
#include "jcode.h"
#include <QMessageBox>
#include <QFile>
#include <QDir>
#include <QDebug>
#include <QSplitter>
#include <QHttpMultiPart>
#include <QFileDialog>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QFileInfo>
#include <QDesktopServices>

FormPZ_FJ::FormPZ_FJ(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormPZ_FJ)
{
    ui->setupUi(this);
    //this->setMinimumSize(1280,700);
    this->show();
    //QMessageBox::information(NULL, "信息", "进入凭证附件界面！！");
    Start();
    if (mySQL::SendString!=""){
        PZH=mySQL::SendString.toInt(); //接受传递进来的凭证编号！！
        mySQL::SendString="";
        LoadTree(mySQL::ND,PZH);
    }else{
        this->close(); //无传递参数进来就自动关闭
    }

}
bool FormPZ_FJ::DownLoadFile(QString FileUrl,QString LocalFile)
{
   QUrl url(FileUrl);
   QNetworkAccessManager manager;
   QEventLoop loop;
   // qDebug() << "图片下载地址： " << GifUrl;
   QNetworkReply *reply = manager.get(QNetworkRequest(url));
   //请求结束并下载完成后，退出子事件循环
   QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   //开启子事件循环
   loop.exec();
   QByteArray Filemsg = reply->readAll();

       QFile file(LocalFile);
       if(!file.open(QFile::WriteOnly))
       {
           qDebug() << "open file fail";
           exit(1);
       }
       file.write(Filemsg);
       file.close();
       return true;

}
void FormPZ_FJ::LoadTree(QString ND,int PZBH){
    //保存到数据库里面
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    //先读取凭证总表 获取ZBID
    QString SQL="";
    int ZBID=0;
    SQL="select zbid from pzzb ";
    SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZBH);
    query.exec(SQL);
    while(query.next()){
        ZBID=query.value("zbid").toInt();
    }
    ui->treeWidget->clear();
    ui->treeWidget->setHeaderLabels(QStringList() << "文件名"  << "上传者" << "上传日期" <<"idd" );
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度

    if (ZBID!=0){
        SQL="SELECT idd,type_id,type,type_idd,username,upload_date,filename FROM upfiles ";
        SQL+=QString(" where type_id='%1' and type_idd='%2' and type='凭证附件' ORDER BY upload_date ").arg(mySQL::TypeId).arg(ZBID);
        query.exec(SQL);
        while(query.next()){
            QStringList child;
            child<<query.value("filename").toString();
            child<<query.value("username").toString();
            child<<query.value("upload_date").toDateTime().toString("yyyy-MM-dd hh:mm:ss");
            child<<query.value("idd").toString();
            QTreeWidgetItem * citem =new QTreeWidgetItem(child);
            citem->setCheckState(0, Qt::Unchecked);
            ui->treeWidget->addTopLevelItem(citem);
        }

        //检查发票信息
        ui->treeWidgetFP->clear();
        ui->treeWidgetFP->setHeaderLabels(QStringList() << "发票类型" << "发票代码" <<"发票号码" <<"金额（去税）" << "上传者" << "上传日期" );
        ui->treeWidgetFP->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
        SQL="select invoice_type,invoice_code,invoice_no,invoice_date,amount,info,username,input_date from invoice_info ";
        SQL+=QString(" where type_id='%1' and reidd='%2' and type='记账凭证' ORDER BY input_date ").arg(mySQL::TypeId).arg(ZBID);

        //SQL+=QString(" where type_id='%1' and invoice_code='%2' and invoice_no='%3'  ").arg(mySQL::TypeId).arg(ui->txtFPDM->text()).arg(ui->txtFPH->text());

        query.exec(SQL);
        while(query.next()){

            QStringList child;
            child<<query.value("invoice_type").toString();
            child<<query.value("invoice_code").toString();
            child<<query.value("invoice_no").toString();
            child<<QString::number(query.value("amount").toDouble(),'f',2);
            child<<query.value("username").toString();
            child<<query.value("input_date").toString();
            QTreeWidgetItem * citem =new QTreeWidgetItem(child);
            //citem->setCheckState(0, Qt::Unchecked);
            ui->treeWidgetFP->addTopLevelItem(citem);
        }
    }


}
void FormPZ_FJ::Start()
{
    ui->tabWidget->setTabPosition(QTabWidget::North);//设置选项卡的方位东南西北，默认在上方
    ui->tabWidget->setTabText(0,"电子文档");
    ui->tabWidget->setTabText(1,"电子发票");
    ui->tabWidget->setCurrentIndex(0);

    ui->cmbFPLX->clear();
    ui->cmbFPLX->addItem("01-增值税专用发票");
    ui->cmbFPLX->addItem("04-增值税普通发票");
    ui->cmbFPLX->addItem("10-增值税电子普通发票");
    //进入界面后删除pdftmp下所有文件！！
    QString del_file = QDir::currentPath();

    del_file+="/pdftmp";
    if (JCode::clearTempFiles(del_file)==true){
        qDebug() << "清除临时文件成功！";
    }



}
FormPZ_FJ::~FormPZ_FJ()
{
    delete ui;
}

void FormPZ_FJ::on_btnCamera_clicked()
{
    FormCam * formCAM =new class FormCam;
    formCAM->show();
    connect(formCAM,SIGNAL(sendData(QString)),this,SLOT(receiveData(QString)));
}
void FormPZ_FJ::receiveData(QString data){
    //QMessageBox::information(NULL, "信息", data);
    QDateTime curDateTime=QDateTime::currentDateTime();
    QFile file1(data);
    QDir *folder = new QDir;
    QString aFile = QDir::currentPath();

    QString pdfPath =QString("%1/pdftmp").arg(aFile);
    folder->mkdir(pdfPath);
    QString FileName=QString("pz_%1.pdf").arg(curDateTime.toString("yyyyMMdd-hhmmss"));
    pdfPath+=QString("/%1").arg(FileName);
    file1.copy(pdfPath);
    QString url=QString("http://%1/up_file/upfileCW.php").arg(mySQL::ServerWEB);
    //QSting 转换一下
    QByteArray ba2;
    ba2.append(mySQL::UserName);     //也可以 ba2 = s2.toLatin1();
    const char* SN=ba2.data();
    FileUPload(url,pdfPath,SN);
}

void FormPZ_FJ::on_btnReturn_clicked()
{
    this->close();
}
void FormPZ_FJ::uploadFinished()
{
    // 获取数据
    if (QNetworkReply::NoError == reply->error()){
        QByteArray context = reply->readAll();
        //QTextCodec* pCodec = QTextCodec::codecForName("UTF-8");
        //QString strResult = pCodec->toUnicode(context);//输出返回的文本

        QJsonObject result_obj = QJsonDocument::fromJson(context).object();
        QString Filename = result_obj.value("filename").toString();
        qDebug()<<"filename:"<<Filename<<result_obj;
        QString str=QString("文件上传成功！！\n文件名:%1").arg(Filename);
        QMessageBox::information(NULL, "信息", str);
        //保存到数据库里面
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        //先读取凭证总表
        QString SQL="";
        int ZBID=0;
        SQL="select zbid from pzzb ";
        SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(mySQL::ND).arg(PZH);
        query.exec(SQL);
        while(query.next()){
            ZBID=query.value("zbid").toInt();
        }
        //str=QString("ZBID=%1").arg(ZBID);
        //QMessageBox::information(NULL, "信息", str);
        if(ZBID>0){
            QDateTime curDateTime=QDateTime::currentDateTime();
            //QString FileName=QString("pz_%1.pdf").arg(curDateTime.toString("yyyyMMdd-hhmmss"));
            SQL="INSERT INTO upfiles(type_id,type,type_idd,username,upload_date,filename) VALUES (";
            SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
            SQL+=QString("'%1',").arg("凭证附件");
            SQL+=QString("'%1',").arg(ZBID);
            SQL+=QString("'%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
            SQL+=QString("'%1',").arg(curDateTime.toString("yyyy-MM-dd hh:mm:ss"));
            SQL+=QString("'%1')").arg(Filename);
            str=QString("SQL=%1").arg(SQL);
            //qDebug()<<SQL;
            //QMessageBox::information(NULL, "信息", str);
            query.exec(SQL);
            LoadTree(mySQL::ND,PZH); //保存成功后刷新附件列表
        }
    }
    else{
        //qDebug()<<"error string:"<<reply->errorString();
        QString str=QString("文件上传失败！！\n错误信息:%1").arg(reply->errorString());
        QMessageBox::information(NULL, "信息", str);
        reply->deleteLater();
    }
}

void FormPZ_FJ::FileUPload(QString url,QString FileName,const char * SN)
{
        QString uploadFilename=FileName;//上传路径,可自定义
        //QMessageBox::information(NULL, "信息", uploadFilename);
        QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

        QHttpPart imagePart;
        QFile *file = new QFile(uploadFilename);
        file->open(QIODevice::ReadOnly);
        imagePart.setBodyDevice(file);
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html"));//设置上传文件类型
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + file->fileName() + "\""));
        multiPart->append(imagePart);

        QHttpPart dataPart;
        //在body体中设置值，
        dataPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"sn\""));
        dataPart.setBody(SN);
        multiPart->append(dataPart);

        QUrl Qurl(url);
        QNetworkRequest request(Qurl);

        QNetworkAccessManager *networkManager= new QNetworkAccessManager;
        reply = networkManager->post(request, multiPart);
        multiPart->setParent(reply);
        //关联槽,上传完成后输出返回信息
        connect(reply,SIGNAL(finished()),this,SLOT(uploadFinished()));

}

void FormPZ_FJ::on_btnFile_clicked()
{
    //打开图片操作
       QString fileName = QFileDialog::getOpenFileName(
                   this, tr("选择图片"),
                   "./",tr("PDF files(*.pdf);;Image files(*.bmp *.jpg *.png );;All file *.* ;"));
       if(fileName.isEmpty())
       {
            QMessageBox mesg;
            mesg.warning(this,"警告","打开图片失败！");
            return;
       }
       else
       {
           QMessageBox::information(NULL, "信息", fileName);
           QFileInfo appInfo(fileName);
           //QMessageBox::information(NULL, "文件名", appInfo.baseName());
           //QMessageBox::information(NULL, "//扩展名", appInfo.suffix());
           QString fileType=appInfo.suffix();
           QDateTime curDateTime=QDateTime::currentDateTime();
           QFile file1(fileName);
           QDir *folder = new QDir;
           QString aFile = QDir::currentPath();

           QString pdfPath =QString("%1/pdftmp").arg(aFile);
           folder->mkdir(pdfPath);
           QString FileName=QString("pz_%1.%2").arg(curDateTime.toString("yyyyMMdd-hhmmss")).arg(fileType);
           pdfPath+=QString("/%1").arg(FileName);
           file1.copy(pdfPath);
           QString url=QString("http://%1/up_file/upfileCW.php").arg(mySQL::ServerWEB);
           //QSting 转换一下
           QByteArray ba2;
           ba2.append(mySQL::UserName);     //也可以 ba2 = s2.toLatin1();
           const char* SN=ba2.data();
           FileUPload(url,pdfPath,SN);

       }

}

void FormPZ_FJ::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int i=column;
    i++;
    i--;
    QString url=QString("http://%1/up_file/uploadFinancial/%2/%3").arg(mySQL::ServerWEB).arg(item->text(1)).arg(item->text(0));
    QString Localfile=QString("%1/pdftmp/%2").arg(QDir::currentPath()).arg(item->text(0));
    //QMessageBox::information(NULL, "文件名", url);
    //QMessageBox::information(NULL, "文件名", Localfile);
    if (DownLoadFile(url,Localfile)==true){
        QDesktopServices::openUrl(QUrl::fromLocalFile(Localfile));
    }
}
void FormPZ_FJ::GetHTTP(QString Url){
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    QNetworkRequest request;
    request.setUrl(QUrl(Url));
    Httpreply = manager->get(request);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinish(QNetworkReply*)));
}
void FormPZ_FJ::replyFinish(QNetworkReply* reply)
{
    qDebug()<<reply->readAll();
}

void FormPZ_FJ::on_btnDelFile_clicked()
{
    QTreeWidgetItemIterator it(ui->treeWidget);
        while (*it) {
            if ((*it)->checkState(0)==Qt::Checked){
                QString str="";
                str=QString("确认删除文件【%1】录吗？ 删除后是无法恢复的！！！！").arg((*it)->text(0));
                if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
                    str=QString("http://%1/up_file/movefile.php?%2/%3").arg(mySQL::ServerWEB).arg((*it)->text(1)).arg((*it)->text(0));
                    //QMessageBox::information(NULL, "文件名", str);
                    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
                    //先读取凭证总表
                    QString SQL="";
                    SQL=QString(" delete from upfiles where idd=%1").arg((*it)->text(3));
                    query.exec(SQL);
                    GetHTTP(str);
                }

            }
            ++it;
        }
        LoadTree(mySQL::ND,PZH);
}


void FormPZ_FJ::keyPressEvent(QKeyEvent *keyevent){

    if(QApplication::focusWidget() == ui->txtYSXX) {
        int uKey = keyevent->key();
        Qt::Key key = static_cast<Qt::Key>(uKey);
        if(key==Qt::Key_Return || key==Qt::Key_Enter ){
            //通过判断回车来保存电子发票条形码
            QString str=ui->txtYSXX->text();
            //QMessageBox::information(NULL, "文件名", str);
            QStringList FPinfo =str.split("，");
            ui->txtFPDM->setText("");
            ui->txtFPH->setText("");
            ui->txtFPJE->setText("");
            ui->txtRQ->setText("");
            if (FPinfo.count()>8){
                //获取完整信息后开始保存
                //for (int i=0; i<sl.count(); i++)
                //    qDebug() << sl.at(i);
                //先找到发票类型
                for (int i=0; i<ui->cmbFPLX->count(); i++){
                    if (ui->cmbFPLX->itemText(i).left(2)==FPinfo.at(1)){
                        ui->cmbFPLX->setCurrentIndex(i);
                    }
                }
                ui->txtFPDM->setText(FPinfo.at(2));
                ui->txtFPH->setText(FPinfo.at(3));
                ui->txtFPJE->setText(FPinfo.at(4));

                QString tmp=FPinfo.at(5).left(4);
                tmp+="-";
                tmp+=FPinfo.at(5).mid(4,2);
                tmp+="-";
                tmp+=FPinfo.at(5).mid(6,2);
                ui->txtRQ->setText(tmp);
                QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
                QString SQL="";
                int InvoiceCount=0;

                //检查发票是否已经被登记了
                SQL="select reidd from invoice_info ";
                SQL+=QString(" where type_id='%1' and invoice_code='%2' and invoice_no='%3'  ").arg(mySQL::TypeId).arg(ui->txtFPDM->text()).arg(ui->txtFPH->text());

                query.exec(SQL);
                while(query.next()){

                    InvoiceCount++;
                }
                if (InvoiceCount==0){
                    int ZBID=0;
                    //获取总表ID
                    SQL="select zbid from pzzb ";
                    SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(mySQL::ND).arg(PZH);
                    query.exec(SQL);
                    while(query.next()){
                        ZBID=query.value("zbid").toInt();
                    }
                    //开始保存
                    if(ZBID>0){
                        QDateTime curDateTime=QDateTime::currentDateTime();

                        SQL="insert into invoice_info(";
                        SQL+="type_id,type,reidd,invoice_type,invoice_code,invoice_no,invoice_date,amount,info,username,input_date";
                        SQL+=") values(";
                        SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg("记账凭证");
                        SQL+=QString("'%1',").arg(ZBID);
                        SQL+=QString("'%1',").arg(ui->cmbFPLX->currentText().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ui->txtFPDM->text().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ui->txtFPH->text().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(tmp.trimmed().replace("'","''"));
                        SQL+=QString("%1,").arg(ui->txtFPJE->text().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ui->txtYSXX->text().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
                        SQL+=QString("'%1')").arg(curDateTime.toString("yyyy-MM-dd hh:mm:ss"));

                        //qDebug() << SQL;
                        query.exec(SQL);
                        //QMessageBox::information(NULL, "信息", "保存成功！");
                        LoadTree(mySQL::ND,PZH);
                    }
                }else{
                    tmp=QString("发票：%1 已经使用过了%2次，请查询！！").arg(ui->txtFPH->text()).arg(InvoiceCount);
                    QMessageBox::information(NULL, "信息", tmp);
                }


            }
        }
    }
}
